#!/bin/bash 
# 设置命令标题名称
echo -ne "\e]2;银河麒麟V10Sp1工具箱\a"

# 确保脚本在终端中运行
if [ -z "$TERM" ]; then
    # 如果没有终端，尝试启动一个终端来运行脚本
    x-terminal-emulator -e "$0"
    exit 0
fi

# 颜色定义
red='\033[0;31m' 
green='\033[0;32m' 
yellow='\033[0;33m'
blue='\033[0;34m' 
cyan='\033[0;36m'
magenta='\033[0;35m' 
reset='\033[0m'
nc='\033[0m'

# 优化图标路径检查
icon_path="/usr/share/icons/hicolor/48x48/apps/xq-kylin-tools.png"
[[ ! -f "$icon_path" ]] && icon_path=""  # 图标不存在时不显示

# ====================== 通知工具函数 ======================
# 桌面通知与终端提示函数
show_notification() { 
    local title="$1" message="$2" level="$3" icon="${4:-}"
    case "$level" in
        "success") color="$green"; urgency="normal" ;;
        "warning") color="$yellow"; urgency="normal" ;;
        "error")   color="$red"; urgency="critical" ;;
        *)         color="$nc"; urgency="normal" ;;
    esac
    echo -e "\n${color}【$title】${message}${NC}"
    # 发送桌面通知
    if command -v notify-send &> /dev/null; then
        if [[ -n "$icon" && -f "$icon" ]]; then
            notify-send -u "$urgency" -i "$icon" "$title" "$message" 2>/dev/null || true
        else
            notify-send -u "$urgency" "$title" "$message" 2>/dev/null || true
        fi
    fi
}

# ====================== 权限检查与获取函数 ======================
# 错误处理函数 - 防止闪退并提示用户
handle_error() {
    local message="$1"
    echo -e "\n${red}【错误】${message}${NC}"
    show_notification "操作失败" "${message}" "error" "$icon_path"
    read -p "按Enter键继续或关闭窗口..."  # 防止闪退，等待用户确认
}
echo -e "${blue}▶ 正在验证sudo权限，请输入您的密码...${NC}"

if sudo -v; then
    echo -e "\n${green}【成功】sudo权限验证通过，继续执行后续操作${NC}"
else
    echo -e "\n${red}【错误】sudo权限验证失败！原因可能是：${NC}" 
    echo -e "${yellow}1. 当前用户未配置sudo权限"
    echo -e "2. 密码输入错误"
    exit 1
fi

# 用户确认函数：提示用户确认操作（y/n），返回 0（确认）或 1（取消）
confirm_operation() {
    echo -en "${yellow}$1 (y/n): ${reset}"
    read -r response
    [[ "$response" =~ ^[Yy]$ ]] && return 0 || return 1  
}

# ====================== 5）系统故障修复菜单开始 ======================
# 系统故障修复菜单：处理各类系统故障
system_menu() {
    while true; do
        clear
         echo -e "${blue}======================  银河麒麟工具箱  =====================${reset}"
        echo -e "${green}╔══════════════════════════════════════════════════════════╗"
        echo -e "║                         系统故障修复                     ║"
        echo -e "╚══════════════════════════════════════════════════════════╝${reset}"              
        echo -e " ${magenta} 1)${reset} 应用程序闪退修复          ${magenta} 2)${reset} 鼠标无法点击修复"
        echo -e " ${magenta} 3)${reset} 桌面图标丢失修复          ${magenta} 4)${reset} 登录循环问题修复"
        echo -e " ${magenta} 5)${reset} 软件商店异常修复          ${magenta} 6)${reset} 桌面登录问题修复"
        echo -e " ${magenta} 7)${reset} 输入法异常的修复          ${magenta} 8)${reset} 解决卸载不全问题"        
        echo -e " ${magenta} 9)${reset} 永久关闭安全限制          ${magenta}10)${reset} 修复浮动窗口卡住"          
        echo -e " ${magenta}11)${reset} 系统漏洞搜索工具          ${magenta}12)${reset} 强制删除异常文件"    
        echo -e " ${magenta}13)${reset} 回收站文件异常修复        ${magenta}14)${reset} 解决密钥环的异常"    
        echo -e " ${magenta}15)${reset} 解决双击计算机闪退        "    
        
        echo -e " \n" 
        echo -e " ${magenta} a)${reset} 任务栏问题修复"            
        echo -e " ${red} 0)${reset} 返回主菜单"

        echo -e "${blue}$(printf '═%.0s' $(seq 1 60))${reset}"
        echo -en "${yellow}请输入选项编号 [ 例如：1 ] : ${reset}"
        read -rp "" choice
        case $choice in
            1) fix_app_crash; echo -e "\n${yellow}按Enter键继续...${reset}"; read -r ;;
            2) fix_mouse_click; echo -e "\n${yellow}按Enter键继续...${reset}"; read -r ;;
            3) fix_desktop_icons_missing; echo -e "\n${yellow}按Enter键继续...${reset}"; read -r ;;
            4) fix_login_loop; echo -e "\n${yellow}按Enter键继续...${reset}"; read -r ;;
            5) fix_software_store; echo -e "\n${yellow}按Enter键继续...${reset}"; read -r ;;
            6) fix_desktop_login; echo -e "\n${yellow}按Enter键继续...${reset}"; read -r ;;
            7) fix_input_method; echo -e "\n${yellow}按Enter键继续...${reset}"; read -r ;;            
            8) clean_residual_packages; echo -e "\n${yellow}按Enter键继续...${reset}"; read -r ;;        
            9) permanently_disable_security_restrictions; echo -e "\n${yellow}按Enter键继续...${reset}"; read -r ;;         
            10) fix_floating_window_freezing; echo -e "\n${yellow}按Enter键继续...${reset}"; read -r ;;            
            11) fix_check_cve; echo -e "\n${yellow}按Enter键继续...${reset}"; read -r ;;       
            12)fix_force_delete ;;     
            13)fix_recycle_file;  echo -e "\n${yellow}按Enter键继续...${reset}"; read -r ;;    
            14)fix_gnome_keyring;  echo -e "\n${yellow}按Enter键继续...${reset}"; read -r ;;    
            15)fix_control_center ;  echo -e "\n${yellow}按Enter键继续...${reset}"; read -r ;;  
            a) taskbar_fix_menu;  break ;;
            0) echo -e "${green}→ 正在返回主菜单...${reset}";  break ;;
            *) echo -e "${red}✗ 无效选择，请重新输入！${reset}"; sleep 0.5 ;;
        esac
        echo -e "\n${yellow}按Enter键继续...${reset}"
        read -r
    done
}
# ====================== 系统故障修复功能 ======================
# 应用程序闪退修复：重置用户配置并重启桌面服务
fix_app_crash() {
    echo -e "${cyan}>>> 正在修复应用程序闪退问题...${reset}"
    sudo cp -rf ~/.config  ~/.config_bak
    sudo rm -rf ~/.config
    sudo systemctl restart lightdm   #重启图形界面
    echo -e "${green}[通知] 已重置用户配置，请重新登录测试${reset}"    
}

# 鼠标无法点击修复：重置输入设备配置
fix_mouse_click() {
    echo -e "${cyan}>>> 正在修复鼠标无法点击问题...${reset}"
    sudo cp -rf ~/.config  ~/.config_bak    
    sudo rm -rf ~/.config/ ~/.cache/ ~/.Xauthority
    sudo systemctl restart lightdm
    echo -e "${green}[通知] 已重置输入设备配置${reset}"    
}

# 桌面图标丢失修复：重装桌面管理组件
fix_desktop_icons_missing() {
    echo -e "${cyan}>>> 正在修复桌面图标丢失...${reset}"
    sudo apt reinstall -y  peony  peony-extensions
    echo -e "${green}[通知] 桌面环境已修复，请重启系统${reset}"
}

# 软件商店异常修复：清理APT缓存并重装软件商店
fix_software_store() {
    echo -e "${cyan}>>> 正在修复软件商店异常...${reset}"
    sudo rm -rf /var/lib/apt/lists/*
    sudo apt update
    sudo apt reinstall -y kylin-software-center
    echo -e "${green}[通知] 软件商店服务已重置${reset}"
}

# 网络图标消失修复：重装网络管理组件并重启服务
fix_network_icon_missing() {
    echo -e "${cyan}>>> 正在修复网络图标消失...${reset}"
    sudo apt install -y --reinstall network-manager-gnome
    killall nm-applet
    nm-applet &
    echo -e "${green}[通知] 网络图标已恢复${reset}"
}

# 修复网络图标显示叹号的问题
fix_network_exclamation_icon() {
    echo -e "${cyan}>>> 正在修复网络图标显示叹号...${reset}"
    sudo sed -i '/interval=45/a enabled=false' /etc/NetworkManager/NetworkManager.conf
    sudo  systemctl  restart  NetworkManager
    echo -e "${green}[通知] 网络图标显示叹号已修复${reset}"
}

# 桌面登录问题修复：配置LightDM登录管理器
fix_desktop_login() {
    echo -e "${cyan}>>> 正在修复桌面登录问题...${reset}"
    sudo apt reinstall -y ukui-greeter
    sudo sed -i 's/^greeter-session=.*/greeter-session=ukui-greeter/' /usr/share/lightdm/lightdm.conf.d/95-ukui-greeter.conf
    sudo systemctl restart lightdm
    echo -e "${green}[通知] 登录管理器已重置，重启后生效${reset}"
}

# 输入法无法使用问题修复
fix_input_method() {
    echo -e "${cyan}>>> 正在修复输入法无法使用问题...${reset}"
    sudo apt reinstall  -y  fcitx
    sudo cp -rf  ~/.config/fcitx     ~/.config/fcitx_bak
    sudo rm -rf  ~/.config/fcitx
    echo -e "${green}[通知] 输入法无法使用问题已修复，重启后生效${reset}"
}

# 登录循环问题修复：重置用户权限和Xauthority文件
fix_login_loop() {
    echo -e "${cyan}>>> 正在修复登录循环问题...${reset}"
    sudo rm -f ~/.Xauthority
    sudo chown -R $USER:$USER $HOME
    echo -e "${green}[通知] 用户权限已修复，请重新登录${reset}"
}

# UKUI面板加载失败修复：重装UKUI面板组件
fix_mate_panel() {
    echo -e "${cyan}>>> 正在修复面板加载失败...${reset}"
    sudo apt install -y --reinstall ukui-control-center
    sudo apt install -y --reinstall    ukui-menu    
    sudo systemctl restart lightdm
    echo -e "${green}[通知] UKUI 面板组件已修复${reset}"
}

# 解决卸载不干净的问题
clean_residual_packages() {
       # 显示待清理包
       echo -e "${yellow}以下包将被清理：${nc}"
               to_clean=$(dpkg -l | awk '/^rc/{print $2}')
               [ -z "$to_clean" ] && {
                   echo -e "${green}没有残留配置${nc}\n"
                   read -p "按任意键退出..."
      exit 0
       }
       # 用户确认
       printf "\033[33m确认清理？(Yy/n) \033[0m"
              read reply
              case "$reply" in
                      [Yy]*) ;;
                      *) echo -e "\n${blue}操作取消${nc}"; exit 0 ;;
              esac
       # 执行清理
       echo -e "\n${blue}正在清理...${nc}"
       echo "$to_clean" | xargs sudo apt -y purge && {
            echo -e "\n${green}清理完成${nc}\n"
          } || {
           echo -e "\n${red}清理出错${nc}" >&2
         exit 1
    }
}

# 强制删除软件
force_remove_software() {
    echo -e "${cyan}>>> 强制删除软件...${reset}"
    read -p "请输入要强制删除软件名称: " keyword

    # 检查输入是否为空
    if [ -z "$keyword" ]; then
        echo -e "${yellow}[提示] 未输入软件名称，已退出${reset}"
         echo -e "\n${yellow}按Enter键继续...${reset}"
         read -r
    fi
    sudo dpkg --remove --force-remove-reinstreq  "$keyword"
    sudo dpkg --purge $(dpkg -l | awk '/^rc/{print $2}')
    echo -e "${green}[通知] 已强制删除软件${reset}"
}

# 解决奇安信杀毒软件无法删除的问题
force_remove_qaxsafe() {
    echo -e "${cyan}>>> 解决奇安信杀毒软件无法删除的问题...${reset}"
       sudo rm -rfv  /opt/qaxsafe
       sudo dpkg --remove --force-remove-reinstreq qaxsafe
       sudo dpkg --purge $(dpkg -l | awk '/^rc/{print $2}')
    echo -e "${green}[通知] 已强制删除奇安信杀毒软件${reset}"
}

# 永久关闭安全限制
permanently_disable_security_restrictions() {
    echo -e "${cyan}>>> 永久关闭安全限制...${reset}"
       sudo sed -i 's/security=kysec/security=/g'  /etc/default/grub
       sudo update-grub
       sudo setstatus softmode -p
    echo -e "${green}[通知] 已永久关闭安全限制${reset}"
}

# 修复浮动窗口导致卡死问题
fix_floating_window_freezing() {
    echo -e "${cyan}>>> 正在修复浮动窗口导致卡死问题中...${reset}"
         sudo apt reinstall -y xdg-desktop-portal
         sudo apt reinstall -y xdg-desktop-portal-ukui
         sudo apt reinstall -y bison
         sudo apt reinstall -y flex    
         sudo apt reinstall -y libkylin-disk-encryption
         sudo apt reinstall -y peony-disk-encryption  
    echo -e "${green}[通知] 已修复浮动窗口导致卡死问题${reset}"
}

#系统漏洞搜索工具
fix_check_cve() {
    # 提示用户输入漏洞编号
    read -p "请输入要查询的漏洞编号（例如 CVE-2023-40397）: " cve_id
    # 检查用户是否输入了内容
    if [ -z "$cve_id" ]; then
        echo "错误：漏洞编号不能为空！"
        exit 1
    fi
    # 执行查询命令
    /opt/apps/xq-kylin-tools/submenu/cve_kylinos "$cve_id"
    echo -e "${green}[通知] 系统漏洞搜索已完成${reset}"
}

#强制删除异常文件
fix_force_delete() {
    # 执行查询命令
    /opt/apps/xq-kylin-tools/submenu/force_delete
    echo -e "${green}[通知] 已强制删除异常文件${reset}"
}

#回收站异常文件
fix_recycle_file() {
    # 执行查询命令
    sudo  rm -rf   ~/.local/share/Trash/files/*
    echo -e "${green}[通知] 已修复回收站里文件或文件夹无法删除问题${reset}"
}

fix_gnome_keyring() {
    # 执行查询命令
    sudo  rm  ~/.local/share/keyrings/login.keyring
    echo -e "${green}[通知] 已修复解决密钥环的异常${reset}"
}

fix_control_center() {
    # 解决双击计算机闪退的问题
    sudo  apt reinstall  -y   ukui-control-center
    sudo  apt reinstall  -y   peony
    sudo  apt reinstall  -y   peony-extensions    
    
    sudo rm -rf  ~/.local/share/gvfs-metadata/computer\:
    sudo rm -rf  ~/.local/share/gvfs-metadata/computer
    echo -e "${green}[通知] 已修复双击计算机闪退的问题${reset}"
}


# 任务栏修复子菜单：集中处理任务栏相关问题
taskbar_fix_menu() {
    while true; do  
        clear
        echo -e "${blue}======================  银河麒麟工具箱  =====================${reset}"
        echo -e "${green}╔══════════════════════════════════════════════════════════╗"
        echo -e "║                       任务栏修复工具                     ║"
        echo -e "╚══════════════════════════════════════════════════════════╝${reset}"                     
        echo -e "1) 任务栏消失"
        echo -e "2) 时间显示异常"
        echo -e "3) 图标不显示"
        echo -e "4) 网络图标消失"
        echo -e "5) 网络图标显示叹号"
        echo -e "6) Mate面板加载失败"
        echo -e "7) 解决卸载不干净"
        echo -e "8) 永久关闭安全限制"
        echo -e "0) 返回上级菜单"
        echo -e "══════════════════════════════"
        read -rp "请选择操作: " choice
        case $choice in 
            1)  # 任务栏消失修复
                sudo apt install --reinstall ukui-panel
                ukui-panel --reset &
                echo -e "${green}[通知] 任务栏已重置${reset}"
                echo -e "\n${yellow}按Enter键继续...${reset}"
                read -r
                break
                ;;  
            2)  # 时间显示异常修复
                gsettings set org.ukui.panel clock-visible true
                ukui-panel --reset &
                # 与网络时间同步
                sudo    hwclock   -w
                
                echo -e "${green}[通知] 任务栏时间修复${reset}"
                echo -e "\n${yellow}按Enter键继续...${reset}"
                read -r
                break
                ;;
            3)  # 图标不显示修复
                killall ukui-panel
                ukui-panel &
                echo -e "${green}[通知] 已重置任务栏解决图标${reset}"
                echo -e "\n${yellow}按Enter键继续...${reset}"
                read -r
                break
                ;;
            4)  # 调用网络图标修复函数
                fix_network_icon_missing 
                echo -e "\n${yellow}按Enter键继续...${reset}"
                read -r
                break
                ;;
            5)  # 调用网络图标修复函数
                fix_network_exclamation_icon 
                echo -e "\n${yellow}按Enter键继续...${reset}"
                read -r
                break
                ;;                
            6)  # 调用Mate面板修复函数
                fix_mate_panel 
                echo -e "\n${yellow}按Enter键继续...${reset}"
                read -r
                break
                ;;
            7)  # 解决卸载不干净问题
                clean_residual_packages
                echo -e "\n${yellow}按Enter键继续...${reset}"
                read -r
                break
                ;;
             8) # 永久关闭安全限制
                permanently_disable_security_restrictions
                echo -e "\n${yellow}按Enter键继续...${reset}"
                read -r
                break
                ;;                    
            0)  # 返回上级菜单
                break 
                ;;
            *)  # 无效选择
                echo -e "${red}无效选择！${reset}" 
                sleep 0.5
                ;;
        esac
    done
}
# 执行主函数 
system_menu

# 添加循环保护，防止意外退出
if [ $? -ne 0 ]; then
    echo -e "${red}菜单执行出错，3秒后返回主菜单...${reset}"
    sleep 3
fi
